'''
Function:
	根据电影名在豆瓣电影里搜索电影信息(脚本仅供学习交流，禁止用于其他)
作者:
	loubobooo
'''
import re
import requests
import urllib.parse
from bs4 import BeautifulSoup
import time
import logging

'''根据电影名在豆瓣电影里搜索电影信息'''


class Douban():
    def __init__(self):
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
            'Host': 'movie.douban.com',
        }
        self.search_url = 'https://movie.douban.com/j/subject_suggest?q={}'

    """
      __  __            _
     |  \/  |          (_)
     | \  / | _____   ___  ___
     | |\/| |/ _ \ \ / / |/ _ \\
     | |  | | (_) \ V /| |  __/
     |_|  |_|\___/ \_/ |_|\___|
    """
    '''外部调用'''

    def run(self):
        with open('movieinfo.txt', mode='r', encoding='utf-8') as f:
            rows = f.readlines()
            for row in rows:
                # 电影搜索
                row_split = row.split(',')
                length = len(row_split)
                movie_name = row.rstrip("\n") if length < 2 else row_split[length - 2].rstrip("\n")
                print('[INFO-豆瓣]请输入需要查询的电影名: ' + movie_name)
                if movie_name == 'restart':
                    return False
                print(self.search_url.format(urllib.parse.quote(movie_name)))
                res = requests.get(self.search_url.format(urllib.parse.quote(movie_name)), headers=self.headers)
                results = res.json()
                data = dict()
                if len(results) == 0:
                    print('[INFO-豆瓣]未能查询到相关关键字的电影信息.')

                for idx, result in enumerate(results):
                    print('——> %d. %s(%s年)' % (idx, result.get('title'), result.get('year')))
                    data[str(idx)] = result.get('url')
                # 获得电影详情
                movie_idx = '0' if length <= 1 else row_split[length - 1].rstrip("\n")
                url = data.get(movie_idx)
                if url is None:
                    print('[INFO-豆瓣]您的输入有误, 请重新输入.')
                    continue
                else:
                    movie_info = requests.get(url, headers=self.headers).text
                    movie = self.start_parser(movie_info)
                    print(movie)
                    logging.info(movie)
                time.sleep(15)

    def get_celebrity_info(self, node):
        celebrity_nodes = node.next_sibling.next_sibling.find_all('a')
        celebrities = [
            {
                'name': celebrity.string,
                'douban_id':
                    re.findall(r'\d+', celebrity['href'])[0]
                    if re.match(r'/celebrity/\d+/', celebrity['href']) else None
            } for celebrity in celebrity_nodes
        ]

        return celebrities

    def get_movie_info(self, node_dict):
        movie_info = {}
        # if '导演' in node_dict:
        #     movie_info['directors'] = self.get_celebrity_info(node_dict['导演'])
        #
        # if '编剧' in node_dict:
        #     movie_info['playwrights'] = self.get_celebrity_info(node_dict['编剧'])

        # if '主演' in node_dict:
        #     movie_info['actors'] = self.get_celebrity_info(node_dict['主演'])

        if '类型' in node_dict:
            genres = []
            node = node_dict['类型']
            node = node.next_sibling
            while (node.name != 'br'):
                if node.name == 'span':
                    genres.append(
                        {
                            'name': node.string
                        }
                    )
                node = node.next_sibling

            movie_info['genres'] = genres

        # if '官方网站' in node_dict:
        #     movie_info['official_site'] = \
        #         node_dict['官方网站'].next_sibling.next_sibling.get('href')

        if '制片国家/地区' in node_dict:
            movie_info['countries'] = [
                {
                    'name': name.strip()
                } for name in node_dict['制片国家/地区'].next_sibling.string.split('/')
            ]

        # if '语言' in node_dict:
        #     movie_info['languages'] = [
        #         {
        #             'name': name.strip()
        #         } for name in node_dict['语言'].next_sibling.string.split('/')
        #     ]
        #
        # if '上映日期' in node_dict:
        #     movie_info['pubdate'] = \
        #         node_dict['上映日期'].next_sibling.next_sibling.string
        #
        # if '片长' in node_dict:
        #     movie_info['duration'] = \
        #         node_dict['片长'].next_sibling.next_sibling.string
        #
        # if '又名' in node_dict:
        #     movie_info['aliases'] = [
        #         name.strip()
        #         for name in node_dict['又名'].next_sibling.string.split('/')
        #     ]
        #
        # if 'IMDb链接' in node_dict:
        #     movie_info['imdb_number'] = \
        #         node_dict['IMDb链接'].next_sibling.next_sibling.string
        #
        # if '集数' in node_dict:
        #     total_count = node_dict['集数'].next_sibling.string.strip()
        #     movie_info['total_count'] = total_count

        return movie_info

    def start_parser(self, text):
        data = {
            'title': '',
        }

        s = BeautifulSoup(text, "lxml")
        try:
            data['title'] = s.select('#content h1 span')[0].string
            data['douban_rate'] = s.select('.rating_num')[0].string
        except IndexError:
            print(data)

        # data['thumbnail_photos'] = [
        #     photo.get('src')
        #     for photo in s.find(id='related-pic').find_all('img')
        # ]
        # if s.find(property='v:summary'):
        #     data['summary'] = s.find(property='v:summary').string

        info_node_dict = {}
        info_nodes = s.select('.pl')
        for node in info_nodes:
            dict_key = node.string
            if dict_key is not None:
                dict_key = dict_key[:-1] if dict_key.endswith(':') else dict_key
                info_node_dict[dict_key] = node

        data.update(self.get_movie_info(info_node_dict))

        return data


'''run'''
if __name__ == '__main__':
    logging.basicConfig(filename='collection.log', level=logging.INFO)
    douban = Douban()
    douban.run()
